package com.jrauto.CarAppBackend.controller;

/**
 * @author : huiMing
 * Date : 2025年08月18日 14:47
 * @version V1.0
 */
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jrauto.CarAppBackend.entity.Favorite;
import com.jrauto.CarAppBackend.service.FavoriteService;
import com.jrauto.CarAppBackend.utils.R;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/favorite")
public class FavoriteController {

    @Resource
    private FavoriteService favoriteService;

    /**
     * 收藏一辆车 (增)
     * POST /favorites
     * @param favorite 包含 userId 和 carId
     * @return 成功或失败
     */
    @PostMapping
    public R<String> addFavorite(@RequestBody Favorite favorite) {
        // 在插入前，检查该用户是否已收藏过该车辆
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", favorite.getUserId()).eq("car_id", favorite.getCarId());

        if (favoriteService.count(queryWrapper) > 0) {
            return  R.fail("该车辆已被收藏"); // 409 Conflict
        }

        // 设置收藏时间
        favorite.setCreatedAt(LocalDateTime.now());
        boolean success = favoriteService.save(favorite);
        if (success) {
            return  R.ok("收藏成功"); // 201 Created
        }
        return  R.fail("收藏失败"); // 500 Internal Server Error
    }

    /**
     * 取消收藏 (删)
     * DELETE /favorites
     * @param  userId
     * @param  carId
     * @return 成功或失败
     */
    @DeleteMapping
    public R<String> removeFavorite(@RequestParam("userId") Integer userId,
                                    @RequestParam("carId") Integer carId) {
        System.out.println("remove favorite: " + userId);
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("car_id", carId);

        boolean success = favoriteService.remove(queryWrapper);
        if (success) {
            return R.ok("取消收藏成功");
        }
        return R.fail("取消收藏失败，未找到记录"); // 404 Not Found
    }

    /**
     * 获取某个用户的所有收藏列表 (查)
     * GET /favorites/user/{userId}
     * @param userId 用户ID
     * @return 收藏列表
     */
    @GetMapping("/user/{userId}")
    public List<Favorite> getFavoritesByUserId(@PathVariable Integer userId) {
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).orderByDesc("created_at"); // 按收藏时间倒序
        return favoriteService.list(queryWrapper);
    }

    /**
     * 新增接口：判断用户是否已收藏某辆车
     * GET /favorites/status?userId={userId}&carId={carId}
     * @param userId 用户ID
     * @param carId 车辆ID
     * @return 如果已收藏返回 true，否则返回 false
     */
    @GetMapping("/status")
    public R<Boolean> getFavoriteStatus(@RequestParam("userId") Integer userId, @RequestParam("carId") Integer carId) {
        boolean isFavorite = favoriteService.isCarFavoritedByUser(userId, carId);
        return R.ok(isFavorite);
    }
}
